package com.thortec.farmsys.utils;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class IpUtils {

    /**
     * 获取本机IP
     */
    public static String getLocalIP() {
        String eth[]={"eth0","eth1"};
        String ip = "";
        for(int index=0;index<eth.length;index++){
            try {
                if(isLinux()){
                    Enumeration<?> e1 = (Enumeration<?>) NetworkInterface
                            .getNetworkInterfaces();
                    while (e1.hasMoreElements()) {
                        NetworkInterface ni = (NetworkInterface) e1.nextElement();
                        if (!ni.getName().equals(eth[index])) {
                            continue;
                        } else {
                            Enumeration<?> e2 = ni.getInetAddresses();
                            while (e2.hasMoreElements()) {
                                InetAddress ia = (InetAddress) e2.nextElement();
                                if (ia instanceof Inet6Address)
                                    continue;
                                ip = ia.getHostAddress();
                            }
                            break;
                        }
                    }
                }else{
                    ip = InetAddress.getLocalHost().getHostAddress().toString();
                    if(StringUtil.isNotEmpty(ip)) break;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return ip;
    }

    /**
     * 判断是linux系统还是其他系统
     * 如果是Linux系统，返回true，否则返回false
     */
    public static boolean isLinux() {
        return System.getProperty("os.name").toLowerCase().indexOf("linux") >= 0;
    }
}
